﻿using System;
using System.Collections.Generic;
using System.Linq;
using Entalpy.dto;


namespace Entalpy.Model
{
    public class DataPreparer : IDataPreparer
    {

        public IDictionary<double, double> GetRelation(IList<Data> Data)
        {
            IDictionary<double, double> Relation = new Dictionary<double, double>();

            foreach (Data d in Data)
            {
                if (!Relation.ContainsKey(1000 / d.Temperature))
                {
                    Relation.Add(1000 / d.Temperature, Math.Log(d.Temperature * d.Intensity + 0.01)); // а если интенсивность = 0 ?
                }
            }

            Relation = Relation.OrderBy(pair => pair.Key).ToDictionary(pair => pair.Key, pair => pair.Value); ;
            return Relation;
        }

        public double[] GetLeastSquaresConstants(IDictionary<double, double> Points)
        {
           
            double[,] fmatrix = new double[Points.Count, 2];
            double[] y = new double[Points.Count];

            int i = 0;
            foreach (var point in Points)
            {
                fmatrix[i, 0] = point.Key;
                fmatrix[i, 1] = 1;

                y[i++] = point.Value;
            }
            
            int info;
            double[] c; // коэффициенты
            alglib.lsfitreport rep;
            alglib.lsfitlinear(y, fmatrix, out info, out c, out rep);

            return c;    
        }

        public IDictionary<double, double> GetLeastSquaresPoints(IDictionary<double, double> Points)
        {
            double[] constant = GetLeastSquaresConstants(Points);

            IDictionary<double, double> MyPoints = new Dictionary<double, double>();
           
            foreach (var point in Points)
            {
                MyPoints.Add(point.Key, point.Value * constant[0] + constant[1]);
            }


            return MyPoints.OrderBy(pair => pair.Key).ToDictionary(pair => pair.Key, pair => pair.Value); 
        }

        public double GetDelta(IDictionary<double, double> Points, IDictionary<double, double> Results)
        {
            double delta = 0;

            foreach (var point in Points)
                delta += Math.Pow((point.Value - Results[point.Key]),2);
            return delta;
        }


     
    }
}
